<?php
class ConnectionModel extends ModelArray
{
    protected static $instance;

    public static function GetInstance()
    {
        return self::$instance ? self::$instance : self::$instance = new ConnectionModel();
    }

    public static function GetDefaultId()
    {
        $id = self::GetInstance()->GetIdByFieldValue('isdefault', 1);
        if (!$id)
            throw new DBNoDefaultConnectionException();
        return $id;
    }

    public function GetDefault($fields = null)
    {
        return $this->FindById($this->GetDefaultId(), $fields);
    }

    public function GetDefaultSchema()
    {
        return $this->GetSchemaById($this->GetDefaultId());
    }

    public function GetSchemaById($id)
    {
        return $this->FindScalarById($id, 'database');
    }

    public function Update($item)
    {
        $default_id = self::GetInstance()->GetIdByFieldValue('isdefault', 1);
        $id = parent::Update($item);
        if ($default_id != $id && isset($item['isdefault']) && $item['isdefault']) $this->UnDefault($default_id);
        return $id;
    }

    public function Insert($item)
    {
        $default_id = self::GetInstance()->GetIdByFieldValue('isdefault', 1);
        $id = parent::Insert($item);
        if ($default_id && isset($item['isdefault']) && $item['isdefault']) $this->UnDefault($default_id);
        return $id;
    }

    protected function UnDefault($id)
    {
        $item['id'] = $id;
        $item['isdefault'] = 0;
        $this->Update($item);
    }

    protected function LoadFields()
    {
        $this->AddField('id', 'varchar', false, true);
        $this->AddField('host');
        $this->AddField('login');
        $this->AddField('password');
        $this->AddField('database');
        $this->AddField('encoding', 'varchar', false, false, 'utf8');
        $this->AddField('isdefault', 'bool');
    }
}
?>